package com.kc.data.common.resolver;


import com.kc.data.common.annotation.UserId;
import com.kc.data.common.base.StringUtils;
import com.kc.data.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@UserId注解的方法参数，注入当前登录用户id
 *
 * @author wangdl
 */
@Component
@Slf4j
public class UserIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(UserId.class);
    }

    @Override
    public Integer resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                   NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空
        if (StringUtils.isBlank(token)) {
            return null;
        }

        Claims claims = jwtUtils.getClaimByToken(token);
//        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
//            return null;
//        }
        if (claims == null) {
            return 0;
        }
        return Integer.parseInt(claims.getSubject());
    }
}
